<?php
class Schedule_Model_Event extends Promotor_Model_Scaffold
{
	protected $_dbTableClass = 'Schedule_Model_DbTable_Event';
	
	protected $_cachedMethods = array(
		'findEvents',
		'findOneBy' // parent::findOneBy
	);
	
	public function findEvents($schedule, $username = null)
	{
		$result = array();

		if (null === ($schedule = $this->_getScheduleId($schedule)))
		{
			$this->_setStatus(self::FAILURE);
			return $result;
		}

		$table = $this->getDbTable();
		$select = $table->select()
						->where('schedule_id = ?', $schedule);

		if (null !== ($username = $this->_getUsernameId($username)))
		{
			$select->where('user_id = ?',  $username);
		}
		
		try {
			$stmt = $select->query();
			$this->_setStatus(self::SUCCESS);
		} catch(Zend_Db_Exception $e) {
			$this->_addException($e);
			$this->_setStatus(self::FAILURE);
		}
		
		$date = new Zend_Date();
		while ($row = $stmt->fetch())
		{
			$date->set($row['start']);
			$row['start'] = $date->getIso(Zend_Date::ISO_8601);
			
			$date->set($row['end']);
			$row['end'] = $date->getIso(Zend_Date::ISO_8601);

			$result[] = $row;
		}
		
		return $result;
	}
	
	protected function _getScheduleId($identificator)
	{
		if (is_numeric($identificator))
		{
			return $identificator;
		}
		
		if (is_string($identificator))
		{
			$schedule = new Schedule_Model_Schedule();
			/* @var $row Zend_Db_Table_Row */
			if (null !== ($row = $schedule->findOneBy('username', $identificator)))
			{
				return $row->id;
			}
		}
	}
	
	protected function _getUsernameId($identificator)
	{
		if (is_numeric($identificator))
		{
			return $identificator;
		}
		
		if (is_string($identificator))
		{
			$schedule = new Schedule_Model_User();
			
			/**
			 * TODO: username poo name to zarzynka!
			 * nie zaimplemtowanej nazwy skrutowej! 
			 */
			
			/* @var $row Zend_Db_Table_Row */
			if (null !== ($row = $schedule->findOneBy('name', $identificator)))
			{
				return $row->id;
			}
		}
	}
}